package demo.web;

import com.alibaba.fastjson.JSONObject;
import demo.vo.common.ApiResult;
import demo.vo.common.User;
import demo.service.MongoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@RestController
public class DemoRestController {

    private static final Logger logger = LoggerFactory.getLogger(DemoRestController.class);
    Random random = new Random();

    //    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //    @Autowired
    private MongoService mongoService;


    @GetMapping("/")
    public ApiResult<String> index(HttpServletRequest request) {
        return new ApiResult<>("WELCOME");
    }

    @GetMapping("/test/form")
    public ApiResult<Object> testForm(HttpServletRequest request) {
        String[] ids = request.getParameterValues("ids[]");
        return new ApiResult<>(ids);
    }

    @GetMapping("/mongo/{table}/{id}")
    public ApiResult<Object> testMongo(@PathVariable("table") String table, @PathVariable("id") String id) {
        Object vo = mongoService.queryCollectionById(table, id);
        return new ApiResult<>(vo);
    }

    @GetMapping("/mongodb/{table}/{id}")
    public ApiResult<Object> findMongoById(@PathVariable("table") String table, @PathVariable("id") String id) {
        JSONObject vo = mongoService.findCollectionById(table, id);
        return new ApiResult<>(vo);
    }

    @GetMapping("/redis/{key}")
    public ApiResult<String> testRedis(HttpServletRequest request, @PathVariable("key") String key) {
        ValueOperations<String, String> vo = stringRedisTemplate.opsForValue();
        String t = vo.get(key);
        return new ApiResult<>(t);
    }

    @RequestMapping("/login")
    public ApiResult<Integer> adminLogin(HttpServletRequest request, HttpServletResponse response) {
        ApiResult<Integer> result = new ApiResult<>();
        Object user = request.getAttribute("user");
        if (user == null) {
            user = request.getParameter("user");
        }

        if (user == null) {
            return new ApiResult<>(-1, "need Login");
        } else {
            request.getSession().setAttribute("user", user);
            result.setData(1);
        }
        return result;
    }

    @PostMapping("/demo/user")
    public ApiResult<Integer> saveUser(@RequestBody User request) {
        ApiResult<Integer> result = new ApiResult<>();
        if (request == null) {
            return new ApiResult<>(-1, "arguments is null.");
        }
        System.out.println(request.toString());
        result.setData(0);
        return result;
    }

    @GetMapping("/demo/user/ids")
    public ApiResult<List<User>> getUserById(@RequestParam("id") Integer[] ids) {
        logger.info("query users by ids={}", Arrays.toString(ids));
        List<User> users = new ArrayList<>();
        for (Integer integer : ids) {
            users.add(new User(integer, "User_" + integer));
        }
        return new ApiResult<>(users);
    }

    @GetMapping("/demo/user/id/{id}")
    public ApiResult<User> getUserById(HttpServletRequest request, @PathVariable("id") Integer id) {
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        ApiResult<User> result = new ApiResult<>();
        logger.info("query user by id={}", id);
        id = 0Xab;
        result.setData(new User(id, "Name" + sessionId));
        return result;
    }

    @GetMapping(value = "/demo/user/list")
    public ApiResult<List<User>> queryUserBy(@RequestParam(name = "id", required = false) Integer id,
                                             @RequestParam(name = "name", required = false) String name) {
        ApiResult<List<User>> result = new ApiResult<>();
        System.out.printf("find by id %d, name %s", id, name);
        List<User> list = new ArrayList<User>();
        list.add(new User(0, "Stan0"));
        list.add(new User(1, "Stan1"));
        result.setData(list);
        return result;
    }

    @DeleteMapping("/demo/user/delete/{id}")
    public ApiResult<Integer> deleteUserById(@PathVariable("id") Integer id) {
        ApiResult<Integer> result = new ApiResult<>();
        logger.info("query user by id={}", id);
        result.setData(0);
        return result;
    }

}
